<?php
namespace backend\models;
/**
 * @author Xianan Huang
 *
 */
use Yii;
use yii\base\Model;
class ItemForm extends Model {
    public $name;
    public $type;
    public $description;

    const T_ROLE = 1;   //角色
    const T_POWER = 2;  //权限

    //定义场景
    const SCENARIOS_CREATE = 'create';
    const SCENARIOS_DELETE = 'delete';

    public function rules() {
        return [
            [['name', 'type'], 'required'],
            ['name', 'filter', 'filter' => 'trim'],
            ['name', 'unique', 'targetClass' => '\common\models\AuthItemModel', 'message' => '此名称已经被占用。', 'on' => self::SCENARIOS_CREATE],
            ['type', 'integer'],
            [['name', 'description'], 'string', 'max' => 25]
        ];
    }

    public function attributeLabels() {
        return [
            'name' => '名称',
            'type' => '类型',
            'description' => '描述',
        ];
    }

    /**
     * 场景设置
     * @see \yii\base\Model::scenarios()
     */
    public function scenarios() {
        $scenarios = [
            self:: SCENARIOS_CREATE => ['name', 'type', 'description'],
            self:: SCENARIOS_DELETE => ['name'],
        ];
        return array_merge(parent:: scenarios(), $scenarios);
    }

    //添加角色/权限
    public function addItem()
    {
        $auth = Yii::$app->authManager;
        if($this->type == self::T_ROLE){
            $item = $auth->createRole($this->name);
            $item->description = $this->description?:'创建['.$this->name.']角色';
        }else{
            $item = $auth->createPermission($this->name);
            $item->description = $this->description?:'创建['.$this->name.']权限';
        }
        return $auth->add($item);
    }

    //给角色赋予权限
    public function addItemChild($data, $name = null){
        $authManager = \Yii::$app->authManager;
        $role = $authManager->getRole(isset($name)?$name:$this->name);
        foreach($data as $v){ //一条条添加权限
            $node = $authManager->getPermission($v);
            if(!$node)continue;
            $authManager->addChild($role, $node);
        }
        return true;
    }

    //删除角色对应的权限
    public function removeItemChild($data, $name = null){
        $authManager = \Yii::$app->authManager;
        $role = $authManager->getRole(isset($name) ? $name : $this->name);
        foreach($data as $v){ //一条条移除
            $node = $authManager->getPermission($v);
            if(!$node)continue;
            $authManager->removeChild($role, $node);
        }
    }

    //删除角色/权限
    public function romoveItem()
    {
        if($this->validate()){
            $auth = Yii::$app->authManager;
            $item = $auth->getRole($this->name)?:$auth->getPermission($this->name);
            return $auth->remove($item);
        }
       return false;
    }
}